<?php

namespace App\Http\Controllers\Saas;

use App\Http\Config\ErrorCode;
use App\Models\Admin\AdminUser;
use App\Models\Saas\Mall;
use App\Models\Saas\UserManager;
use App\Models\video\CommonServer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/** 后台系统管理 */
class MallController extends BaseController
{
    private $field = ["name" => "require", "manager_id" => 0,  "admin_id" => 0, "expired_time" => null]; //填入数据库需要存储的表字段
    private $fieldMsg = ["name" => "系统名"];
    private $data = [];

    // 系统列表
    public function getPageList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = $request['page'] ? $request['page'] : 1;
        $pageSize = $request['pageSize'] ? $request['pageSize'] : 10;
        //搜索条件
        if(!$this->is_su){ // 不是超管，只显示自己的账号列表
            $filter[] = ["m.manager_id", "=", $this->AU["id"]];
        }
        $filter[] = ["m.is_delete", "=", (isset($request["deleteStatus"]) && $request["deleteStatus"] == "1") ? "1" : "0"];
        $query = Mall::query()->from(Mall::query()->getModel()->getTable()." as m")
            ->leftJoin(UserManager::query()->getModel()->getTable()." as u", "m.manager_id", "=", "u.id")
            ->where($filter);
        if(!empty($request['search'])){
            $query->whereRaw("m.name like '%{$request["search"]}%' or u.username like '%{$request["search"]}%'");
        }
        $data['count'] = $query->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data['list'] = $query->select("m.id","m.name","m.expired_time","m.create_time","m.manager_id","m.is_disable","u.username as userAccount", "m.type")
            ->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("create_time", "desc")->get();
        if($data['list']){
            $data['list'] = Mall::transferField($data['list']->toArray());
        }
        if($data["list"]) {
            $url = CommonServer::getUrl();
            foreach ($data['list'] as &$item) {
                $item["createTime"] = date("Y-m-d H:i", $item["createTime"]);
                if($item["type"] == "crm") {
                    $item["userCount"] = DB::table("admin_users")->where(["mall_id" => $item["id"]])->count();
                    $item["orderCount"] = DB::table("achievement")->where(["mall_id" => $item["id"]])->count();
                }else{
                    $item["userCount"] = DB::table("up_user")->where(["mall_id" => $item["id"]])->count();
                    $item["orderCount"] = DB::table("up_order")->where(["mall_id" => $item["id"], "status" => 2])->count();
                }
                $item["managerUrl"] = $item["isDisable"] == '0' ? $url."/index.html#/homepage/index?SaaSToken={$request["token"]}&SaaSId={$item["id"]}" : '';
                $item["userUrl"] = $item["isDisable"] == '0' ? "{$url}/agent/#/login?SaaSId={$item["id"]}" : '';
                if(!empty($item["expiredTime"])){
                    if($item["expiredTime"] < time()){
                        $item["managerUrl"] = '';
                        $item["userUrl"] = '';
                    }
                    $item["expiredTime"] = date("Y-m-d", $item["expiredTime"]);
                }else{
                    $item["expiredTime"] = "永久";
                }
            }
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    // 添加
    public function toAdd(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        foreach ($this->field as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($request[$ks])) {
                return $this->return_result(ErrorCode::code("params_not_exist", $this->fieldMsg[$k]));
            }
            $this->data[$k] = isset($request[$ks]) ? trim($request[$ks]) : $v;
        }
        $this->data["manager_id"] = $this->AU["id"];
        $adminUserModel = new AdminUser();
        $userData = UserManager::query()->where("id", $this->AU["id"])->select(["password", "username"])->first();
        $id = $adminUserModel->adminUserInsert(["password" => $userData->password, "name" => $userData->username, "position" => "超级管理员"]);
        if(!$id){
            $this->returnData = ErrorCode::code("customized", "添加账户失败");
        }
        $this->data["admin_id"] = $id;
        $mall = Mall::getFields("type", ["is_delete" => 0], true, false);
        $this->data["type"] = $mall["type"];
        $res = Mall::toAdd($this->data, true);
        if(isset($res["code"])){
            return $this->return_result($res);
        }
        $adminUserModel->newQuery()->where("id", $id)->update(["mall_id" => $res]);
        DB::table('configs')->insert(['mall_id' => $res, "title" => $this->data["name"] ?: "crm", "env" => !empty($scf_data["IS_SCF"]) ? "CLOUD" : "LOCAL", "site_status" => 1]);
        if($mall["type"] == "crm") {
            DB::table("annual_leave")->insert(['mall_id' => $res]);
            DB::table('home_page')->insert([
                ['mall_id' => $res, "name" => "轮播", "position" => "1", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 1, 'auth_id' => 1],
                ['mall_id' => $res, "name" => "公告", "position" => "2", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 1, 'auth_id' => 2],
                ['mall_id' => $res, "name" => "插件", "position" => "3", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 1, 'auth_id' => 3],
                ['mall_id' => $res, "name" => "推荐", "position" => "4", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 1, 'auth_id' => 5],
                ['mall_id' => $res, "name" => "新闻", "position" => "5", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 1, 'auth_id' => 4],
                ['mall_id' => $res, "name" => "导航", "position" => "6", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 1, 'auth_id' => 11],
                ['mall_id' => $res, "name" => "轮播", "position" => "1", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 2, 'auth_id' => 6],
                ['mall_id' => $res, "name" => "公告", "position" => "2", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 2, 'auth_id' => 7],
                ['mall_id' => $res, "name" => "插件", "position" => "3", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 2, 'auth_id' => 8],
                ['mall_id' => $res, "name" => "推荐", "position" => "4", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 2, 'auth_id' => 10],
                ['mall_id' => $res, "name" => "新闻", "position" => "5", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 2, 'auth_id' => 9],
                ['mall_id' => $res, "name" => "导航", "position" => "6", "status" => 1, 'updated_at' => Carbon::now(), 'type' => 2, 'auth_id' => 12],
            ]);
        }
        $this->returnData["msg"] = "添加成功";
        return $this->return_result($this->returnData);
    }

    // 获取信息
    public function getInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "系统ID"));
        }
        $data = Mall::getFields("id,name,manager_id", ["id" => $request["id"]]);
        if($data){
            if(!$this->is_su && $data["managerId"] != $this->AU["id"]){
                return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
            }
            unset($data["managerId"]);
            $this->returnData["data"] = $data;
        }else{
            $this->returnData["data"] = [];
        }
        return $this->return_result($this->returnData);
    }

    // 更新
    public function toUpdate(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "系统ID"));
        }
        foreach ($this->field as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($request[$ks])) {
                return $this->return_result(ErrorCode::code("params_not_exist", $this->fieldMsg[$k]));
            }
            if (isset($request[$ks])) {
                $this->data[$k] = trim($request[$ks]);
            }
        }
        if(!isset($this->data["expired_time"])){
            $this->data["expired_time"] = null;
        }
        $adminData = UserManager::query()->where(["id" => $this->AU["id"]])->select(["type"])->first();
        if ($adminData["type"] == '2') { // 由其它系统创建的账号不允许修改
            unset($this->data["expired_time"]);
        }
        if($this->is_su) {
            $res = Mall::doUpdate($this->data, ["id" => $request["id"]]);
        }else{
            $res = Mall::doUpdate($this->data, ["id" => $request["id"], "manager_id" => $this->AU["id"]]);
        }
        if(isset($res["code"])){
            return $this->return_result($res);
        }
        $this->returnData["msg"] = "修改成功";
        return $this->return_result($this->returnData);
    }

    // 回收系统
    public function toRecycle(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "系统ID"));
        }
        if(!isset($request["deleteStatus"]) || !in_array($request["deleteStatus"], ["0", "1"])){
            return $this->return_result(ErrorCode::code("params_error", "status"));
        }
        $this->data["is_delete"] = $request["deleteStatus"];
        if($this->is_su) {
            $res = Mall::doUpdate($this->data, ["id" => $request["id"]]);
        }else{
            $res = Mall::doUpdate($this->data, ["id" => $request["id"], "manager_id" => $this->AU["id"]]);
        }
        if(isset($res["code"])){
            return $this->return_result($res);
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "状态更新失败";
        }else {
            $this->returnData["msg"] = "状态更新成功";
        }
        return $this->return_result($this->returnData);
    }

    // 删除系统
    public function toDelete(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "系统ID"));
        }
        $res = Mall::delById($request["id"], $this->is_su, $this->AU["id"]);
        if(isset($res["code"])){
            return $this->return_result($res);
        }
        $this->returnData["msg"] = "删除成功";
        return $this->return_result($this->returnData);
    }

    // 更新状态
    public function toDisable(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "系统ID"));
        }
        if(!isset($request["status"]) || !in_array($request["status"], ["0", "1"])){
            return $this->return_result(ErrorCode::code("params_error", "status"));
        }
        $this->data["is_disable"] = $request["status"];
        if($this->is_su) {
            $res = Mall::doUpdate($this->data, ["id" => $request["id"]]);
        }else{
            $res = Mall::doUpdate($this->data, ["id" => $request["id"], "manager_id" => $this->AU["id"]]);
        }
        if(isset($res["code"])){
            return $this->return_result($res);
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "状态更新失败";
        }else {
            $this->returnData["msg"] = "状态更新成功";
        }
        return $this->return_result($this->returnData);
    }

    // 迁移
    public function toMigrate(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "系统ID"));
        }
        if(empty($request['managerId'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "管理员ID"));
        }
        if(!$this->is_su) {
            return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
        }
        $res = Mall::doUpdate(["manager_id" => $request["managerId"]], ["id" => $request["id"]]);
        if(isset($res["code"])){
            return $this->return_result($res);
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "迁移失败";
        }else {
            $this->returnData["msg"] = "迁移成功";
        }
        return $this->return_result($this->returnData);
    }
}